package com.simple.datax.flow.processor;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.alibaba.dubbo.common.logger.Logger;
import com.alibaba.dubbo.common.logger.LoggerFactory;
import com.simple.datax.api.MessageService;
import com.simple.datax.flow.constants.ProcessResultConstants;
import com.simple.datax.flow.convertor.Convertor;
import com.simple.datax.flow.dao.ibatis.model.FlowActors;
import com.simple.datax.flow.message.BaseEcMessage;
import com.simple.datax.flow.message.EcFlowMessage;
import com.simple.datax.flow.message.EcFlowRespMessage;
import com.simple.datax.flow.service.FlowActorsManager;

/**
 * @Title: MessageServiceImpl.java
 * @Package com.simple.datax.flow.processor
 * @Description: TODO(流程处理器)
 * @author tonney
 * @date 2013-1-3 下午02:17:47
 * @version V1.0
 */
public class MessageServiceImpl implements MessageService {
	public Logger log = LoggerFactory.getLogger(this.getClass());
	
	private EcFlow201MessageProcessor ecFlow201MessageProcessor = null;

	private EcFlow201RespMessageProcessor ecFlow201RespMessageProcessor = null;
	
	private Convertor messageConvertor;
	
	private FlowActorsManager flowActorsManager = null;

	public void setFlowActorsManager(FlowActorsManager flowActorsManager) {
		this.flowActorsManager = flowActorsManager;
	}

	public void setMessageConvertor(Convertor messageConvertor) {
		this.messageConvertor = messageConvertor;
	}

	public void setEcFlow201MessageProcessor(
			EcFlow201MessageProcessor ecFlow201MessageProcessor) {
		this.ecFlow201MessageProcessor = ecFlow201MessageProcessor;
	}

	public void setEcFlow201RespMessageProcessor(
			EcFlow201RespMessageProcessor ecFlow201RespMessageProcessor) {
		this.ecFlow201RespMessageProcessor = ecFlow201RespMessageProcessor;
	}

	@Override
	public void service(String xmlcode) {
		int result = ProcessResultConstants.STATUS_PROC_EXCEPTION;
		BaseEcMessage message = null;
		try {
			if (xmlcode != null) {
				log.debug("recv Message<=="+xmlcode);
				/***************************** 报文转换成对象 BEGIN ******************************************/
				message = messageConvertor.convert2EcMessage(xmlcode); // 报文转换为对象
				if(message!=null){
					result = validMessageHead(message);
					if(result==ProcessResultConstants.STATUS_SUCCESS){
						message.setOrgXmlCode(xmlcode);
						if(message instanceof EcFlowMessage){		
							result = ecFlow201MessageProcessor.process(message);
						}else if(message instanceof EcFlowRespMessage){
							result = ecFlow201RespMessageProcessor.process(message);
						}else{
							log.warn("MessageServiceImpl::service warn=> Unknow Message Type");
						}
					}
				}else { // 解析失败，无法生成报文只能打出系统错误日志
					log.error("MessageServiceImpl::service error=> Message can not convert");
					return; // 如果无法转换直接退出
				}
				
			} else {
				result = ProcessResultConstants.STATUS_MESSAGE_NULL;
				log.warn("MessageServiceImpl::service warn=> Message Content is null");
			}
		} catch (Exception e) {
			// 如果执行到此步,说明有异常,则返回错误报文给发送者
			result = ProcessResultConstants.STATUS_PROC_EXCEPTION;
			log.error("MessageServiceImpl::service error==>" + e.toString());
		} finally {
			if(result!=ProcessResultConstants.STATUS_SUCCESS){
				log.error("MessageServiceImpl::service process fail,result is " + ProcessResultConstants.getProcDetail(result));
			}else{
				log.info("process end!");
			}
		}
	}
	
	public int validMessageHead(BaseEcMessage ecMessage){
		int result = ProcessResultConstants.STATUS_SUCCESS;
		String recvAddr = null;
//		String recvid = null;
		String sendAddr = null;
//		String sendid = null;
//		String flowid = null;
		try{
			if(ecMessage instanceof EcFlowMessage){		
				EcFlowMessage ecFlowMessage = (EcFlowMessage)ecMessage;
				recvAddr = ecFlowMessage.getFlowMessageHead().getReceiverAddress();
				sendAddr = ecFlowMessage.getFlowMessageHead().getSenderAddress();
//				sendid = ecFlowMessage.getFlowMessageHead().getSenderId();
//				recvid = ecFlowMessage.getFlowMessageHead().getReceiverId();
//				flowid = ecFlowMessage.getFlowMessageBody().getFlowId();
			}else if(ecMessage instanceof EcFlowRespMessage){
				EcFlowRespMessage ecFlowRespMessage = (EcFlowRespMessage)ecMessage;
				recvAddr = ecFlowRespMessage.getFlowRespMessageHead().getReceiverAddress();
				sendAddr = ecFlowRespMessage.getFlowRespMessageHead().getSenderAddress();
//				sendid = ecFlowRespMessage.getFlowRespMessageHead().getSenderId();
//				recvid = ecFlowRespMessage.getFlowRespMessageHead().getReceiverId();
//				flowid = ecFlowRespMessage.getFlowRespMessageBody().getEcFlowResponseHead().getBpNo();
			}else{
				result = ProcessResultConstants.STATUS_UNKNOWN_MESSAGETYPE;
				log.warn("MessageServiceImpl::service warn=> Unknow Message Type");
			}
			if((recvAddr.equals("")||recvAddr.split("@").length<2)||(sendAddr.equals("")||sendAddr.split("@").length<2)){
				result = ProcessResultConstants.STATUS_EC_ADDRESS_WRONG;
			}
//			else{
//				List<FlowActors> actorsList = flowActorsManager.getFlowActorListByFlowid(flowid);
//				Map<String,String> map = new HashMap<String,String>();
//				for(FlowActors flowActor:actorsList){
//					map.put(flowActor.geteCode(),flowActor.geteNode());
//				}
//				if (map.get(sendid) == null
//						|| map.get((sendAddr.split("@"))[0]) == null
//						|| (!(sendAddr.split("@"))[1].equals(map.get(sendid)))
//						|| (!(sendAddr.split("@"))[0].equals(sendid))) {
//					result = ProcessResultConstants.STATUS_EC_ADDRESS_WRONG;
//				}
//			}
		}catch(Exception e){
			result = ProcessResultConstants.STATUS_PROC_EXCEPTION;
			log.error("BaseMessageProcessor::validMessageHead error==>"
					+ e.toString());
		}
		return result;
	}

}
